package cn.zyk.filter;

import cn.zyk.util.*;
import com.auth0.jwt.interfaces.*;
import jakarta.servlet.*;
import jakarta.servlet.annotation.*;
import jakarta.servlet.http.*;
import lombok.extern.slf4j.*;
import org.springframework.stereotype.*;

import java.io.*;
import java.util.*;

/**
 * @Author eHlw
 * @Date 2024/9/13 21:32
 * @description:
 */

@Slf4j
@WebFilter(filterName = "JwtFilter", urlPatterns = "/*")
//@Configuration
@Component
public class JwtFilter implements Filter {

    private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<>(
            Arrays.asList("/user/login", "/user/getToken")));

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;
        String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");
        boolean allowedPath = ALLOWED_PATHS.contains(path);
        response.setCharacterEncoding("UTF-8");
        //获取 header里的token
        final String token = request.getHeader("eHlwToken");

        if (allowedPath) {
            chain.doFilter(req, res);
        } else if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            chain.doFilter(request, response);
        } else {
            if (token == null) {
                response.setStatus(500);
                response.getWriter().write("{\"code\":500, \"message\":\"TOKEN不存在\"}");
                response.setHeader("content-type", "applicastion/json");
                return;
            }

            Map<String, Claim> userData = JwtUtil.verifyToken(token);
            if (userData == null) {
                response.setStatus(500);
                response.getWriter().write("{\"code\":500, \"message\":\"TOKEN校验失败\"}");
                response.setHeader("content-type", "applicastion/json");
                return;
            }
            String username = userData.get("username").asString();
            String passwd = userData.get("passwd").asString();
            //拦截器 拿到用户信息，放到request中
            request.setAttribute("username", username);
            request.setAttribute("passwd", passwd);
            chain.doFilter(req, res);
        }
    }

    @Override
    public void destroy() {
    }


}